#!/usr/bin/env python

import numpy as np
import os, serial,time,socket,sys,json
from meas_data import meas_data
from w1thermsensor import W1ThermSensor
# import the server implementation
sensor="w1therm"
pathname = os.path.dirname(sys.argv[0])        
abspath=os.path.abspath(pathname)

idfile=abspath+"/id.json"
id_conf=0
try:
	idf=open(idfile,"r")
	id_conf=json.load(idf)['id']
	idf.close()
except:
	id_conf=0

configfile=abspath+"/config.json"
try:
	cf=open(configfile,"r")
except:
	cf=open(configfile+".template","r")

log_conf=json.load(cf)
cf.close()

channel_names=[]
channel_info={}

parameter={"device":socket.gethostname(),"deviceid":"FF","mean_count":5,"ring_length":10,"wait":0.5,"cycle":10,"check_last":5,"check_last_shrinking":0.9,"gpg_keyid":"","digits":3,"store_dir":"/home/pi/log/","multiplicator":1000,"sensor":"w1"}
for n in parameter:
  if n in log_conf:
    parameter[n]=log_conf[n]


# declare w1therm
bw1=False
if sensor in log_conf:
  bw1=True
  w1_conf=log_conf[sensor]
  if "enable" in w1_conf:
    if w1_conf['enable'] == 0:
      bw1=False
  bmqtt=False
  if "mqtt" in log_conf:
    bmqtt=True
    lcmq=log_conf['mqtt']
    mbroker=""
    if 'broker' in lcmq:
      mbroker=lcmq['broker']
    else:
      bmqtt=False
    mport=1883
    if 'port' in lcmq:
      mport=lcmq['port']
  if "sqlserver" in log_conf:
    hostname="localhost"
    port=8080
  if bw1:
    w1={}
    for n in parameter:
      if n in w1_conf:
        parameter[n]=w1_conf[n]
    if "w1" in w1_conf:
      parameter["var_name"]="temperature"
      w1_count=0
      tw1=w1_conf['w1']
      for x in tw1:
        parvar=parameter
        y=tw1[x]
        parvar["i2c"]=int(x,16)%65536
        try:
          w1[x] = W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20, x)
        except:
          print("could not assign W1")
        else:
          parameter["sensor"]="w1/"+x
          channel_info[x]={"meas_data": meas_data(parvar)}
          if bmqtt and ("mqtt" in log_conf[sensor]):
            channel_info[x]['meas_data'].set_mqtt(broker=mbroker,port=mport)
          if "sqlserver" in log_conf:
            channel_info[x]['meas_data'].set_sql(host=hostname,port=port)
          if "opensensemap" in tw1[x]:
            try:
              senseid=tw1[x]["opensensemap"]["sensebox_id"]
            except:
              print("wrong definition of sensemap")
            else:
              try:
                sensor=tw1[x]["opensensemap"]["sensors"]["temperature"]
              except:
                print("wrong definition of sense")
              else:
                channel_info[x]['meas_data'].set_sensebox(senseid,sensor)
          w1_count=w1_count+1
    else:
      bw1=False


if bw1:
      
  while True:
  
    for i in tw1:
      channel_info[i]['meas_data'].append(w1[i].get_temperature())

    time.sleep(parameter['wait'])


# close the client
print("done")


